package models

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"slotGame/utils"
	"strconv"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"github.com/bitly/go-simplejson"
)

type Coin struct {
	Game   string `json:game`
	Amount int    `json:amount`
	Sid    string `json:sid`
}

type CheckCoin struct {
	Code   int      `json:"code"`
	Info   string   `json:"info"`
	Result DataInfo `json:"data"`
}

type DataInfo struct {
	Balance float64 `json:"balance"`
	Nick    string  `json:"nick"`
}

var (
	_game_name = beego.AppConfig.String("game_name")
)

func init() {
	if _game_name == "" {
		_game_name = "示例游戏2"
		beego.Error("配置文件中缺少 game_name 参数")
	}
}

func AddMunisCoin(amount float64, sid string, use string) (result string) {
	beego.Debug(amount, sid)

	var base64Str string

	st := time.Now().Unix()

	stringTime := strconv.FormatInt(st, 10)

	strKey := _game_name + sid + stringTime
	key := utils.GetMd5FromString(strKey) //md5加密32位

	cMap := map[string]string{"game": _game_name, "amount": fmt.Sprint(amount), "key": key}
	postMap, _ := json.Marshal(cMap)

	//	httplib.Post(beego.AppConfig.String("add_munis_coin"))

	//	var r rsa.RsaDecrypt
	if data, err := utils.RsaEncrypt([]byte(string(postMap))); err == nil {

		base64Str = base64.StdEncoding.EncodeToString(data)

		req := httplib.Post(beego.AppConfig.String("add_munis_coin") + sid).Body(base64Str)
		// beego.Debug(base64Str)
		// req.Param("data", base64Str)

		str, err := req.String()
		debase64, _ := base64.StdEncoding.DecodeString(str)
		deRsa, _ := utils.RsaDecrypt(debase64)

		js, _ := simplejson.NewJson([]byte(deRsa))
		bolB, _ := json.Marshal(js)

		s, err := js.Get("code").Int()
		if err == nil {
			coin_log_ := CoinLog{
				Sid:     sid,
				CoinNum: amount,
				Content: string(bolB),
				Use:     use,
			}
			if s == 0 {
				coin_log_.Result = "支付成功"
				result = "Success"
			} else {
				coin_log_.Result = "---> 支付失败"
				result = "fail"
			}
			_, err := coin_log_.AddCoinLog()
			if err != nil {
				beego.Error("插入数据库错误！", err)
			}
			return

		} else {
			return "fail"
		}

	} else {
		return "fail"
	}
}
